package com.example.myapplication13_4;

import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

/**
 * 音乐播放器主活动类
 */
public class MainActivity extends AppCompatActivity {
    
    // 权限请求相关常量
    private static final int PERMISSION_REQUEST_CODE = 123;
    private static final String PERMISSION_STORAGE = android.Manifest.permission.READ_EXTERNAL_STORAGE;
    
    // 播放模式常量
    private static final int MODE_ORDER = 0;  // 顺序播放
    private static final int MODE_REPEAT = 1; // 单曲循环
    
    // UI组件
    private ListView songListView;
    private ImageButton btnPlay;
    private ImageButton btnStop;
    private ImageButton btnLoop;
    private SeekBar seekBar;
    private TextView tvCurrentTime;
    private TextView tvTotalTime;
    private TextView tvSongName;
    
    // 播放器状态
    private MediaPlayer mediaPlayer;
    private final Handler handler = new Handler();
    private boolean isPlaying = false;
    private int playMode = MODE_ORDER;
    private int currentSongIndex = 0;
    
    // 歌曲数据
    private final ArrayList<String> songList = new ArrayList<>();
    private final ArrayList<String> songNames = new ArrayList<>();
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkAndRequestPermissions();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseMediaPlayer();
    }
    
    /**
     * 检查并请求存储权限
     */
    private void checkAndRequestPermissions() {
        if (ContextCompat.checkSelfPermission(this, PERMISSION_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{PERMISSION_STORAGE},
                    PERMISSION_REQUEST_CODE);
        } else {
            initializeApplication();
        }
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, 
            String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                initializeApplication();
            } else {
                showToast("需要存储权限才能播放音乐");
                finish();
            }
        }
    }
    
    /**
     * 初始化应用程序
     */
    private void initializeApplication() {
        initializeViews();
        initializeMediaPlayer();
        setupEventListeners();
        loadMusicFiles();
    }
    
    /**
     * 初始化视图组件
     */
    private void initializeViews() {
        songListView = findViewById(R.id.song_list_view);
        btnPlay = findViewById(R.id.btn_play);
        btnStop = findViewById(R.id.btn_stop);
        btnLoop = findViewById(R.id.btn_loop);
        seekBar = findViewById(R.id.music_seekbar);
        tvCurrentTime = findViewById(R.id.music_current_time);
        tvTotalTime = findViewById(R.id.music_total_time);
        tvSongName = findViewById(R.id.txt_songName);
    }
    
    /**
     * 初始化媒体播放器
     */
    private void initializeMediaPlayer() {
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(mp -> handlePlaybackCompletion());
    }
    
    /**
     * 设置事件监听器
     */
    private void setupEventListeners() {
        setupControlButtons();
        setupSeekBarListener();
        setupSongListListener();
    }
    
    /**
     * 设置控制按钮监听器
     */
    private void setupControlButtons() {
        btnPlay.setOnClickListener(v -> togglePlayPause());
        btnStop.setOnClickListener(v -> stopPlayback());
        btnLoop.setOnClickListener(v -> togglePlayMode());
    }
    
    /**
     * 设置进度条监听器
     */
    private void setupSeekBarListener() {
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser && mediaPlayer != null) {
                    mediaPlayer.seekTo(progress);
                    updateTimeDisplay(progress);
                }
            }
            
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}
            
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });
    }
    
    /**
     * 设置歌曲列表监听器
     */
    private void setupSongListListener() {
        songListView.setOnItemClickListener((parent, view, position, id) -> 
            playSongAtPosition(position));
    }
    
    /**
     * 加载音乐文件
     */
    private void loadMusicFiles() {
        File musicDir = Environment.getExternalStorageDirectory();
        if (!musicDir.exists()) return;
        
        File[] files = musicDir.listFiles((dir, name) -> 
            name.toLowerCase().endsWith(".mp3"));
            
        if (files == null) return;
        
        songList.clear();
        songNames.clear();
        for (File file : files) {
            songList.add(file.getAbsolutePath());
            songNames.add(file.getName());
        }
        
        updateSongListView();
    }
    
    /**
     * 更新歌曲列表视图
     */
    private void updateSongListView() {
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, songNames);
        songListView.setAdapter(adapter);
    }
    
    /**
     * 播放指定位置的歌曲
     */
    private void playSongAtPosition(int position) {
        if (songList.isEmpty()) {
            showToast("没有找到MP3文件");
            return;
        }
        
        currentSongIndex = position;
        String filePath = songList.get(position);
        String songName = songNames.get(position);
        playMusic(filePath, songName);
    }
    
    /**
     * 播放音乐
     */
    private void playMusic(String filePath, String songName) {
        try {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.reset();
            mediaPlayer.setDataSource(filePath);
            mediaPlayer.prepare();
            mediaPlayer.start();
            
            updatePlaybackUI(songName);
        } catch (IOException e) {
            showToast("播放失败：" + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 切换播放/暂停状态
     */
    private void togglePlayPause() {
        if (mediaPlayer != null) {
            if (isPlaying) {
                mediaPlayer.pause();
                btnPlay.setImageResource(R.drawable.play);
            } else {
                mediaPlayer.start();
                btnPlay.setImageResource(R.drawable.pause);
                updateSeekBarProgress();
            }
            isPlaying = !isPlaying;
        }
    }
    
    /**
     * 停止播放
     */
    private void stopPlayback() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            try {
                mediaPlayer.prepare();
                resetPlaybackUI();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * 切换播放模式
     */
    private void togglePlayMode() {
        playMode = (playMode == MODE_ORDER) ? MODE_REPEAT : MODE_ORDER;
        mediaPlayer.setLooping(playMode == MODE_REPEAT);
        btnLoop.setImageResource(playMode == MODE_REPEAT ? 
                R.drawable.repeat : R.drawable.orderplay);
        showToast(playMode == MODE_REPEAT ? "循环播放模式" : "顺序播放模式");
    }
    
    /**
     * 处理播放完成事件
     */
    private void handlePlaybackCompletion() {
        if (playMode == MODE_ORDER && !songList.isEmpty()) {
            int nextIndex = (currentSongIndex + 1) % songList.size();
            playSongAtPosition(nextIndex);
        } else {
            mediaPlayer.start();
        }
    }
    
    /**
     * 更新播放界面
     */
    private void updatePlaybackUI(String songName) {
        isPlaying = true;
        btnPlay.setImageResource(R.drawable.pause);
        tvSongName.setText("正在播放: " + songName);
        seekBar.setMax(mediaPlayer.getDuration());
        updateTimeDisplay(0);
        tvTotalTime.setText(formatTime(mediaPlayer.getDuration()));
        updateSeekBarProgress();
    }
    
    /**
     * 重置播放界面
     */
    private void resetPlaybackUI() {
        seekBar.setProgress(0);
        updateTimeDisplay(0);
        isPlaying = false;
        btnPlay.setImageResource(R.drawable.play);
    }
    
    /**
     * 更新进度条
     */
    private void updateSeekBarProgress() {
        if (mediaPlayer != null && isPlaying) {
            seekBar.setProgress(mediaPlayer.getCurrentPosition());
            updateTimeDisplay(mediaPlayer.getCurrentPosition());
            handler.postDelayed(this::updateSeekBarProgress, 1000);
        }
    }
    
    /**
     * 更新时间显示
     */
    private void updateTimeDisplay(int milliseconds) {
        tvCurrentTime.setText(formatTime(milliseconds));
    }
    
    /**
     * 格式化时间
     */
    private String formatTime(int milliseconds) {
        int seconds = (milliseconds / 1000) % 60;
        int minutes = (milliseconds / 1000) / 60;
        return String.format("%02d:%02d", minutes, seconds);
    }
    
    /**
     * 显示提示信息
     */
    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
    
    /**
     * 释放媒体播放器资源
     */
    private void releaseMediaPlayer() {
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
        handler.removeCallbacksAndMessages(null);
    }
}